﻿using System;
using UnityEngine;

namespace Core
{
    public class SecondTickItem : Core.Component, ITimeTicker
    {
        public Action<int> Func;
        public int Interval;
        public bool Breakup;
        //不受UnityEngine.Time.scale影响
        public bool UnscaledTimeMode;

        private float extraScale;

        public float GetTickScale()
        {
            return extraScale;
        }

        public void SetTickScale(float scale)
        {
            extraScale = scale;
        }

        private float elapsedTime;

        public void Start()
        {
            extraScale = 0;

            if (Breakup)
            {
                //第一次间隔时间，随机在[0,Interval)之间，可以将同时触发的定时器打散，防止某一帧执行压力多大
                elapsedTime = UnityEngine.Random.Range(0, Interval);
            }
            else
            {
                elapsedTime = Interval;
            }
        }

        public void Update()
        {
#if UNITY_EDITOR
            Profiler.Begin("deltatime");
#endif
            if (UnscaledTimeMode)
            {
                elapsedTime -= Time.unscaledDeltaTime * (1 + extraScale);
            }
            else
            {
                elapsedTime -= Time.deltaTime * (1 + extraScale);
            }
#if UNITY_EDITOR
            Profiler.End();

            Profiler.Begin("while");
#endif
            while (elapsedTime <= 0)
            {
                elapsedTime += Interval;
                try
                {
                    Func(Interval);
                }
                catch (Exception e)
                {
                    log.err(e);
                    break;
                }
            }
#if UNITY_EDITOR
            Profiler.End();
#endif
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            Func = null;
            Interval = 0;
            extraScale = 0;
        }
    }
}
